package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.engineer.activity.BalanceActivity;
import com.asktgapp.model.OpenAuthVO;
import com.asktgapp.model.UserInfoVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.AboutUsActivity;
import com.asktgapp.user.activity.AuthenticateActivity;
import com.asktgapp.user.activity.CollectionActivity;
import com.asktgapp.user.activity.MessageCenterActivity;
import com.asktgapp.user.activity.MyFollowActivity;
import com.asktgapp.user.activity.OpinionActivity;
import com.asktgapp.user.activity.PersonalInfoActivity;
import com.asktgapp.user.activity.ServiceOrderActivity;
import com.asktgapp.user.activity.SettingActivity;
import com.asktgapp.utils.ImageDisplayUtil;

import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/8
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class PersnolCenterFragment extends BaseFragment {
    @InjectView(R.id.iv_head)
    ImageView mHeadIMG;
    @InjectView(R.id.tv_info)
    TextView mInfo;
    @InjectView(R.id.tv_auth)
    TextView mAuth;

    @InjectView(R.id.iv_engineer)
    ImageView mEngineerHeadImg;
    @InjectView(R.id.tv_engineer_name)
    TextView mEngineerNametv;

    @InjectView(R.id.tv_personal_attention)
    TextView mAttention;
    @InjectView(R.id.tv_personal_collection)
    TextView mCollection;
    @InjectView(R.id.tv_personal_message)
    TextView mMessage;
    @InjectView(R.id.tv_personal_opinion)
    TextView mOpinion;
    @InjectView(R.id.tv_personal_aboutus)
    TextView mAboutUS;
    @InjectView(R.id.tv_personal_setting)
    TextView mSetting;
    @InjectView(R.id.tv_personal_money)
    TextView mBalance;
    @InjectView(R.id.tv_personal_phone)
    TextView mPhone;
    @InjectView(R.id.rl_personal_money)
    RelativeLayout mEngineerBalance;
    @InjectView(R.id.rl_personal_phone)
    RelativeLayout mEngineerPhone;

    @InjectView(R.id.ll_head_engineer)
    LinearLayout mEngineerHead;

    @InjectView(R.id.ll_head_normal)
    LinearLayout mNormalHead;
    @InjectView(R.id.tv_engineer_tag1)
    TextView mTag1;
    @InjectView(R.id.tv_engineer_tag2)
    TextView mTag2;
    @InjectView(R.id.tv_fenshu1)
    TextView mFenshu1;
    @InjectView(R.id.tv_fenshu2)
    TextView mFenshu2;
    @InjectView(R.id.tv_fenshu3)
    TextView mFenshu3;
    @InjectView(R.id.myOrder)
    TextView myOrder;
    private UserInfoVO mUserInfo;

    private String authStatus = "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_personal_center, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        mHeadIMG.setOnClickListener(this);
        mAuth.setOnClickListener(this);
        mAttention.setOnClickListener(this);
        mCollection.setOnClickListener(this);
        mMessage.setOnClickListener(this);
        mOpinion.setOnClickListener(this);
        mAboutUS.setOnClickListener(this);
        mSetting.setOnClickListener(this);
        mBalance.setOnClickListener(this);
        mEngineerHead.setOnClickListener(this);
        mNormalHead.setOnClickListener(this);
        myOrder.setOnClickListener(this);


    }

    public void showEngineer(boolean show) {
        if (show) {
            mEngineerHead.setVisibility(View.VISIBLE);
            mEngineerBalance.setVisibility(View.VISIBLE);
            mEngineerPhone.setVisibility(View.VISIBLE);
            mNormalHead.setVisibility(View.GONE);
        } else {
            mEngineerHead.setVisibility(View.GONE);
            mEngineerBalance.setVisibility(View.GONE);
            mEngineerPhone.setVisibility(View.GONE);
            mNormalHead.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void loadData() {
        if (MyApplication.userIdIsEmpty(getContext()))
            return;
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        Call<ApiResponseBody<UserInfoVO>> call = apiservice.getUserInfo(params);
        call.enqueue(new Callback<ApiResponseBody<UserInfoVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<UserInfoVO>> call, Response<ApiResponseBody<UserInfoVO>> response) {
                if (response.isSuccessful()) {
                    mUserInfo = response.body().getResult();
                    if (mUserInfo.getHasTixianPwd() == 0) {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_HAS_TX_PWD, false);
                    } else {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_HAS_TX_PWD, true);
                    }
                    if (mUserInfo.getIsEngineer() == 1) {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, true);
                        PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_NAME, mUserInfo.getRealname() + "");

                    } else {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, false);
                        PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_NAME, mUserInfo.getUsername() + "");

                    }
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_PHONE, mUserInfo.getPhone());
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.HEAD_IMG, mUserInfo.getUserPic());
                    if (!Util.isEmpty(mUserInfo.getAuthStatus() + "")) {
                        authStatus = mUserInfo.getAuthStatus();
                    }
                    setUI(mUserInfo);
                } else {

                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<UserInfoVO>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
//                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
//                    showTost(apiException.getMessage(), 0);
                }
            }
        });

    }

    private void setUI(UserInfoVO bean) {
        //工程师和普通用户的个人中心界面有较大差异
        //是否是工程师 1：是; 0：不是
        if (mUserInfo.getIsEngineer() == 1) {
            showEngineer(true);
            mBalance.setText(String.valueOf(bean.getMoney()));
            mPhone.setText(String.valueOf(bean.getPhone()));
            ImageDisplayUtil.loadCircleHeadImage(getActivity(), mEngineerHeadImg, bean.getUserPic());
            mEngineerNametv.setText(bean.getUsername());
            if (Util.isEmpty(bean.getLabel())) {
                mTag1.setVisibility(View.GONE);
                mTag2.setVisibility(View.GONE);
            } else {
                String[] str = bean.getLabel().split(",");
                if (str.length == 0) {
                    mTag1.setVisibility(View.GONE);
                    mTag2.setVisibility(View.GONE);
                } else if (str.length == 1) {
                    mTag1.setVisibility(View.VISIBLE);
                    mTag2.setVisibility(View.GONE);
                    mTag1.setText(str[0]);
                } else if (str.length == 2) {
                    mTag1.setVisibility(View.VISIBLE);
                    mTag2.setVisibility(View.VISIBLE);
                    mTag1.setText(str[0]);
                    mTag2.setText(str[1]);
                } else if (str.length > 2) {
                    mTag1.setVisibility(View.VISIBLE);
                    mTag2.setVisibility(View.VISIBLE);
                    mTag1.setText(str[0]);
                    mTag2.setText(str[1]);
                }
            }
            mFenshu1.setText(String.valueOf(bean.getAttitude()));
            mFenshu2.setText(String.valueOf(bean.getQuality()));
            mFenshu3.setText(String.valueOf(bean.getSpeed()));

        } else {
            showEngineer(false);
            ImageDisplayUtil.loadCircleHeadImage(getActivity(), mHeadIMG, bean.getUserPic());
            mInfo.setText(bean.getUsername() + "    " + bean.getPhone());
            // TODO: 2018/2/5 后台接口忘记写了，等后天写好公共接口，获取是否开放工程师认证入口字段 已经写好了
            // mAuth.setVisibility(View.VISIBLE);
            Apiservice apiservice = ApiUtil.getInstance().create();
            HashMap params = new HashMap();
            Call<ApiResponseBody<OpenAuthVO>> call = apiservice.isOpenAuth(params);
            call.enqueue(new Callback<ApiResponseBody<OpenAuthVO>>() {
                @Override
                public void onResponse(Call<ApiResponseBody<OpenAuthVO>> call, Response<ApiResponseBody<OpenAuthVO>> response) {
                    if (response.isSuccessful()) {
                        OpenAuthVO bean = response.body().getResult();
                        if (bean.getIs_show().equals("0")) {
                            mAuth.setVisibility(View.GONE);
                        } else {
                            mAuth.setVisibility(View.VISIBLE);
                        }
                    } else {
                        showTost(response.raw().message(), 1);
                    }
                }

                @Override
                public void onFailure(Call<ApiResponseBody<OpenAuthVO>> call, Throwable t) {
                    ApiException exception = ExceptionHandle.handleException(t);
                    if (exception.isTokenInvalid()) {
//                        showUnLoginSnackbar();
                    } else if (exception.isNetConnected()) {
                        showSetNetworkSnackbar();
                    } else {
//                        showTost(exception.getMessage(), 0);
                    }
                }
            });
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //头像
            case R.id.ll_head_engineer:
            case R.id.ll_head_normal:
                Intent intent = new Intent(getActivity(), PersonalInfoActivity.class);
                intent.putExtra("name", mUserInfo.getUsername());
                intent.putExtra("head", mUserInfo.getUserPic());
                startActivity(intent);
                break;
            //认证成为工程师
            case R.id.tv_auth:
                if (authStatus.equals("0")) {
                    showTost("您的申请正在审核中，不能再次申请！", 1);
                    return;
                }
                startActivity(new Intent(getActivity(), AuthenticateActivity.class));
                break;
            //我的关注
            case R.id.tv_personal_attention:
                startActivity(new Intent(getActivity(), MyFollowActivity.class));
                break;
            //我的收藏
            case R.id.tv_personal_collection:
                startActivity(new Intent(getActivity(), CollectionActivity.class));
                break;
            //通知中心
            case R.id.tv_personal_message:
                startActivity(new Intent(getActivity(), MessageCenterActivity.class));
                break;
            //意见反馈
            case R.id.tv_personal_opinion:
                startActivity(new Intent(getActivity(), OpinionActivity.class));
                break;
            //关于我们
            case R.id.tv_personal_aboutus:
                startActivity(new Intent(getActivity(), AboutUsActivity.class));
                break;
            //通用设置
            case R.id.tv_personal_setting:
                startActivity(new Intent(getActivity(), SettingActivity.class));
                break;
            //账户余额
            case R.id.tv_personal_money:
                startActivity(new Intent(getActivity(), BalanceActivity.class));

                break;

            case R.id.myOrder:
                startActivity(new Intent(getActivity(), ServiceOrderActivity.class));
                break;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }
}
